package v1

import (
	"supervideo/app/models/category"
	"supervideo/app/requests"
	"supervideo/pkg/response"

	"github.com/gin-gonic/gin"
)

type CategoryController struct {
	BaseAdminController
}

func (zc *CategoryController) Index(c *gin.Context) {
	request := requests.PaginationRequest{}

	if ok := requests.Validate(c, &request, requests.Pagination); !ok {
		return
	}

	data, pager := category.Paginate(c, 10)
	response.JSON(c, gin.H{
		"data":  data,
		"pager": pager,
	})
}

func (zc *CategoryController) Store(c *gin.Context) {
	request := requests.CategoryRequest{}
	if ok := requests.Validate(c, &request, requests.CategoryStore); !ok {
		return
	}

	categoryModel := category.Category{
		Title:    request.Title,
		Sort:     request.Sort,
		Status:   request.Status,
		ParentID: request.ParentID,
		ZoneID:   request.ZoneID,
	}

	categoryModel.Create()
	if categoryModel.ID > 0 {
		response.Created(c, categoryModel)
	} else {
		response.Abort500(c, "创建失败, 请稍后重试~")
	}
}

func (zc *CategoryController) Update(c *gin.Context) {
	categoryModel := category.Get(c.Param("id"))
	if categoryModel.ID == 0 {
		response.Abort404(c)
		return
	}

	request := requests.CategoryRequest{}
	if ok := requests.Validate(c, &request, requests.CategoryStore); !ok {
		return
	}

	categoryModel.Title = request.Title
	categoryModel.Sort = request.Sort
	categoryModel.Status = request.Status
	categoryModel.ParentID = request.ParentID
	categoryModel.ZoneID = request.ZoneID

	rowAffected := categoryModel.Save()
	if rowAffected > 0 {
		response.Data(c, categoryModel)
	} else {
		response.Abort500(c, "更新失败, 请稍后尝试~")
	}

}

func (zc *CategoryController) Delete(c *gin.Context) {
	categoryModel := category.Get(c.Param("id"))
	if categoryModel.ID == 0 {
		response.Abort404(c)
		return
	}

	rowAffected := categoryModel.Delete()
	if rowAffected > 0 {
		response.Success(c)
		return
	}

	response.Abort500(c, "删除失败,请稍后尝试~")

}

func (zc *CategoryController) Show(c *gin.Context) {
	categoryModel := category.Get(c.Param("id"))
	if categoryModel.ID == 0 {
		response.Abort404(c)
		return
	}
	response.Data(c, categoryModel)
}
